﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;


namespace UDownloader
{
    public partial class Form1 : Form
    {
        
        String fileName = "";
        public Form1()
        {
            InitializeComponent();
        }


        /*
         * 列出所有的可用U盘（忽略大于512M的U盘）
         */
        private void ListUDisk()
        {
            DriveInfo[] driveInfo = DriveInfo.GetDrives();
            TargetCombox.Items.Clear();
            foreach (DriveInfo drive in driveInfo)
            {

                if (drive.DriveType == DriveType.Removable                                  //只列出可移动磁盘
                    && (drive.TotalSize <= 536870912))                                      //536870912 = 512MB
                {
                    TargetCombox.Items.Add("[" + drive.VolumeLabel + "] " + drive.Name);    //获取U盘卷标
                    TargetCombox.SelectedIndex = 0;                                         //设置默认选项
                    NameCombox.Items.Add(drive.Name);                                       //添加到列表中去
                    NameCombox.SelectedIndex = TargetCombox.SelectedIndex;
                }

                //记录操作日志，默认记录所有磁盘, 为保护隐私，日志本地保存，不上传服务器

                String temp = "List Driver:" + " \t"
                            + drive.Name.ToString() + "\t"
                            + drive.VolumeLabel.ToString() + "\t"
                            + drive.DriveType.ToString() + "\t" 
                            + drive.DriveFormat +  "\t" 
                            + (drive.TotalFreeSpace/1024/1024).ToString() + "/"
                            + (drive.TotalSize/1024/1024).ToString()+" MB";
                OperateLog(temp);
            }
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            ListUDisk();
        }

        /*
         * 对设备进行编程
         */
        private void Program(FileSystemEventArgs e)
        {
            StatusLabel.Text = "编程中...";

            try
            {
                System.IO.File.Copy(e.FullPath, NameCombox.Text + fileName, true);
                StatusLabel.Text = "完成";
                MessageBox.Show("编程完成", "编程完成", MessageBoxButtons.OK,
                MessageBoxIcon.Information,
                MessageBoxDefaultButton.Button1,
                MessageBoxOptions.ServiceNotification
                );
                OperateLog("Program: \t编程成功");

            }
            catch(Exception ex)
            {
                //错误处理并保存日志文件
                ErrLog(ex);
                MessageBox.Show(ex.Message);
            }
            

        }



        /*
         * 检测文件变化并触发编程操作
         */
        private void FileChangeCB(object source, FileSystemEventArgs e)
        {
            if(AutoDownloadCheckBox.Checked)
            {
                if(DelayCheckBox.Checked)
                {
                    StatusLabel.Text = "延时2s";
                    Thread.Sleep(2000);
                    Program(e);
                }
                else
                {
                    
                }
            }
        }
        private void OpenFileButton_Click(object sender, EventArgs e)
        {
            if(OPD.ShowDialog() == DialogResult.OK)
            {
                String filename = OPD.FileName;
                if(filename == null)
                {
                    MessageBox.Show("空白的文件路径","警告",MessageBoxButtons.OK,MessageBoxIcon.Error);
                }
                else
                {
                    String projectpath = "";
                    FilePathTextBox.Text = filename;
                    String[] temp = filename.Split('\\');
                    for(int i = 0; i < temp.Length -1;i++)
                    {
                        projectpath = projectpath + temp[i] + '\\';
                    }
                    ProjectPathLabel.Text = "工程路径:" + projectpath;
                    fileName = temp[temp.Length - 1].ToString();
                    watcher.Path = projectpath;                                     //想文件监视器中添加文件路径
                    watcher.Filter = fileName ;                                     //像文件监视器中添加文件
                    watcher.Changed += new FileSystemEventHandler(FileChangeCB);    //绑定回调函数
                }
            }
        }

        private void freshButton_Click(object sender, EventArgs e)
        {
            ListUDisk();
        }

        private void TargetCombox_SelectedIndexChanged(object sender, EventArgs e)
        {
         
         
                try
                {
                    NameCombox.SelectedIndex = TargetCombox.SelectedIndex;
                }
                catch(Exception ex)
                {
                    ErrLog(ex);
                }
                    
                }



        /*
         * 错误日志函数
         * 用于记录
         */
        private void ErrLog(Exception ex)
        {
            StreamWriter streamWriter = new StreamWriter("UDownloaderErr.log", append: true);
            String temp = DateTime.Now.ToLocalTime().ToString() + "\t" 
                        + ex.ToString() + "\t" 
                        + FilePathTextBox.Text 
                        + TargetCombox.Text;
            streamWriter.WriteLine(temp);
            streamWriter.Close();                   //释放文件
        }
        private void OperateLog(String Value)
        {
            StreamWriter streamWriter = new StreamWriter("UDownloaderOpe.log", append: true);
            String temp = DateTime.Now.ToLocalTime().ToString() + " \t" + Value;
            streamWriter.WriteLine(temp);
            streamWriter.Close();
        }
    }
}
